import React from 'react'
import _ from 'underscore'
import $ from 'jquery'
import View from 'lib/View.jsx'
import dispatcher from 'lib/dispatcher'
import Grid from 'lib/components/GridWidget.jsx'
import Modal from 'lib/components/Modal.jsx'
import {Scope} from 'lib/scopeFactory'
import {Success,Info,Warning} from 'lib/components/Notify.jsx'
import basicInfo from '../apis/basicInfo'
import UploadFile, {UploadFileStore} from 'lib/components/UploadFile.jsx'

import Select from 'lib/components/Select.jsx';

// Android 限制 10MB 大小，iOS 限制 50MB 大小。
const LIMIT_SIZE = BlueWare.isAndroid ? 1024*1024*10 : 1024*1024*50;

var versionFileColsOption = [{
    title:'版本号',
    key:'appVersionName'
  },{
    title:'文件名',
    key:'fileName'
  },{
    key: 'action',
    render:function(f,rowData){
      function delFile(){
        if(confirm('确定删除这个'+(BlueWare.isAndroid?' proguard 混淆配置':'符号化')+'文件吗？')){
          var params = {
            appVersionId:rowData.appVersionId
          }
          if(BlueWare.isIOS){
            params.id = rowData.id
          }
          $.ajax({
            url:BlueWare.urlPrefix+'/app/'+BlueWare.appId + '/'+(BlueWare.isIOS?'deleteDsym':'delmappingfile')+'.json',
            method:'post',
            data:params
          }).then(function(res){
            if(res.result){
              Success('删除成功')
              dispatcher.dispatch(_.extend({},params,{
                $type:'del_version'
              }))
            }else{
              Warning('删除失败')
            }
          },function(){
            Warning('删除失败')
          })
        }
      }
      return (
        <div className="operation" key={ Math.random() }>
          <a className="iconfont" href="javascript:;" onClick={delFile}>&#xe61f;</a>
        </div>
      )
    }
  }
];

class NewFileDialog extends Modal {
  constructor(props){
    super(props);
    this.state = {
      uploadFileStore: new UploadFileStore()
    }
    this.submit = this.submit.bind(this)
  }
  submit(){
    var _this = this
    if(this.state.saving){
      return ;
    }

    if(!this.state.uploadFileStore.getFiles().length){
      this.setState({
        msg:'请选择上传文件'
      })
      return ;
    }
    this.setState({
      saving:true
    })
    $(this.refs.form).ajaxSubmit({
      dataType:'json'
    }).data('jqxhr').then(function(res){
      if(res.result){
        Success('上传成功')
        if(res.mappingfile&&res.mappingfile.id!==0){//iOS上传id可能为0,Android没有id
          dispatcher.dispatch({
            $type:'add_version_file',
            versionFile:res.mappingfile
          })
        }else{
          window.location.reload()
        }
        _this.close()
      }else{
        this.setState({
          msg:res.msg,
          saving:false
        })
      }
    }.bind(this),function(err){
      this.setState({
        msg:err.responseJSON?err.responseJSON.message:'Error',
        saving:false
      })
    }.bind(this));
  }

  setAppVersionId(item) {
    this.refs.select.value = item.value;
  } // setAppVersionId

  limitFileSizeHandler({ files }) {
    let size = _.reduce(files, (x, y) => x + y.size, 0);

    if (size > LIMIT_SIZE) {
      this.setState({
        msg: `上传的文件超过 ${ LIMIT_SIZE/(1024*1024) }MB 限制，请重新选择。`
      });
      return false;
    }

    if (this.state.msg) {
      this.setState({ msg: '' });
    }
    return true;
  } // limitFileSizeHandler

  renderHeader(){
    return (
      <h4>{'新增'+(BlueWare.isAndroid?' proguard 混淆配置':'符号化')+'文件'}</h4>
    )
  }
  renderBody(){
    let versions = _.map(this.props.versionList, p => ({
      value: p.id,
      label: p.name
    }));

    return (
      <form ref="form"
        action={
          BlueWare.urlPrefix+'/app/'+BlueWare.appId+'/'+
          (BlueWare.isIOS?'uploadDsym':'android_mappingfile')
        } method="post">
        <input type="hidden" name="csrf_token" defaultValue={BlueWare.CSRFTOKEN}/>
        <div className="form-group horizontal">
          <ul style={{marginLeft:'-23px'}}>
            <li>
              <label className="control-label">选择文件版本号</label>
              <div style={{ width: 100, display: 'inline-block' }}>
                <input ref="select" type="hidden" name="appVersionId" value={ versions[0].value } />
                <Select
                  value={ versions[0] }
                  options={ versions }
                  onChange={ this.setAppVersionId.bind(this) } />
              </div>
            </li>
            <li>
              <label className="control-label">选择文件</label>
              <UploadFile
                name="file"
                addCallback={this.limitFileSizeHandler.bind(this)}
                scope={this.state.uploadFileStore}
                error={this.state.msg} />
            </li>
          </ul>
        </div>
      </form>
    )
  }
  renderFooter(){
    return (
      <div>
        {
          this.state.saving?(
            <span>保存中...</span>
          ):(
            <button className="btn-green" onClick={this.submit} type="button">保存</button>
          )
        }
      </div>
    )
  }
}

export let Dialog = NewFileDialog;

class VersionListScope extends Scope{
  constructor(props){
    super(props)
    this.$state = {
      versionFileList:{
        loading:true
      },
      versionList:[]
    }
  }
  $del_version(payload){
    this.$state.versionFileList.data = this.$state.versionFileList.data.filter(function(i){
      return payload.id?(i.id !== payload.id):(i.appVersionId !== payload.appVersionId)
    })
    this.emit()
  }
  $add_version_file(payload){
    this.$state.versionFileList.data.push(payload.versionFile)
    this.emit()
  }
  $load(){
    var _this = this
    basicInfo({
      urlName:'app',
      parentId:BlueWare.appId,
      appId:null
    }).fetch().then(function(data){
      _this.$state.versionList = data.result
      _this.emit()
    });
    if(BlueWare.isIOS){
      $.ajax({
        url:BlueWare.urlPrefix + '/app/'+BlueWare.appId + '/listDsym.json',
        dataType:'json'
      }).then(function(data){
        _this.$state.versionFileList = {
          data:data
        }
        _this.emit()
      })
    }else{
      $.ajax({
        url:BlueWare.urlPrefix + '/app/'+BlueWare.appId + '/mappingfilelist.json',
        dataType:'json'
      }).then(function(data){
        _this.$state.versionFileList = {
          data:data
        }
        _this.emit()
      })
    }
  }
}


export default class VersionListView extends View{
  constructor(props){
    super(props)
    this.showNewFileDialog = this.showNewFileDialog.bind(this)
  }
  render(){
    return (
      <div className="card">
        <h5 className="card-title">
          {
            this.state.versionList.length?(
              <button className="btn-green btn-xs float-right" type="button" onClick={this.showNewFileDialog}>
                新增
              </button>
            ):null
          }
          {BlueWare.isAndroid?'proguard混淆配置文件':'符号化文件'}
        </h5>
        <div style={{
          maxHeight: '300px',
          overflowX: 'hidden',
          overflowY: 'auto'
        }}>
          <Grid cols={versionFileColsOption} store={this.state.versionFileList}/>
        </div>
      </div>
    )
  }
  showNewFileDialog(){
    var versionList = this.state.versionList.filter(function(i){
      return this.state.versionFileList.data?
              (!_(this.state.versionFileList.data).findWhere({appVersionId:i.id})):
              true
    },this)
    if(versionList.length){
      NewFileDialog.mount({
        versionList:versionList
      })
    }else{
      Info(function(notice){
        return (
          <div>
            {'目前所有版本都已存在'+(BlueWare.isAndroid?'proguard混淆配置文件':'符号化文件')+'，请先删除需要重新上传的文件'}
          </div>
        )
      })
    }
  }
}
VersionListView.defaultProps = {
  Scope:VersionListScope
}
